#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <assert.h>

typedef void (*bufferevent_data_cb)(struct bufferevent *bev, void *ctx);

void read_cb(struct bufferevent *bev, void *arg) {
    char buf[512] = {0}, buf1[1024] = {0};
    static int num = 0;
    bufferevent_read(bev, buf, sizeof buf);
    printf("read message %s", buf);
    sprintf(buf1, "[server]: ok %d\n", num++);
    bufferevent_write(bev, buf1, sizeof buf1);
}

void write_cb(struct bufferevent *bev, void *arg) {
    printf("[server]: write finished\n");
}

void event_cb(struct bufferevent *bev, short what, void *arg) {
    if (what & BEV_EVENT_ERROR) {
        printf("some other error\n");
    }
    bufferevent_free(bev);    
    printf("[client]: client connected closed\n"); 
}

void accpet_cb(struct evconnlistener *listener, int fd, struct sockaddr *addr, int socklen, void *arg) {
    struct sockaddr_in client_addr = *(struct sockaddr_in*)addr;
    printf("[server]: connected a new client %s\n", inet_ntoa(client_addr.sin_addr));
    
    struct event_base *evbase = (struct event_base *)arg;
    
    struct bufferevent* bev = bufferevent_socket_new(evbase, fd, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);
    bufferevent_enable(bev, EV_READ);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("usage %s: [port]\n", argv[0]);
        return 0;
    }
    struct event_base *evbase = event_base_new();
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
     
    struct evconnlistener* listener = evconnlistener_new_bind
    (evbase, accpet_cb, (void *)evbase, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 10, (struct sockaddr *)&addr, sizeof addr);

    event_base_dispatch(evbase);

    event_base_free(evbase);

    return 0;
}